package com.sunplus.system.controller.system.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunplus.common.constant.Constants;
import com.sunplus.common.core.domain.AjaxResult;
import com.sunplus.common.core.domain.entity.SysUser;
import com.sunplus.common.core.domain.model.LoginBody;
import com.sunplus.common.core.domain.model.LoginUser;
import com.sunplus.common.utils.ServletUtils;
import com.sunplus.framework.web.service.TokenService;
import com.sunplus.system.mapper.SysUserMapper;
import com.sunplus.system.service.ISysMenuService;
import com.sunplus.system.service.impl.SysLoginService;
import com.sunplus.system.service.impl.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * 登录验证
 */
@RestController
@RequestMapping("/app/")
public class AppSysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("login")
    public AjaxResult login(LoginBody loginBody) {
        System.out.println(JSON.toJSONString(loginBody));
        SysUser sysUser = sysUserMapper.selectUserByUserNameAndType(loginBody.getUsername());
//        SysUser sysUser = sysUserMapper.selectUserByMobile(loginBody.getUsername());
        if(sysUser == null){
            return AjaxResult.error("该用户未注册此平台");
        }
        // 生成令牌
        String login = loginService.loginApp(loginBody.getUsername(), loginBody.getPassword(), loginBody.getVercode(),
                loginBody.getUuid());
        JSONObject token = new JSONObject();
        token.put(Constants.TOKEN, login);
        token.put(Constants.JWT_USERID, sysUser.getPID());
        return AjaxResult.success(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }


}
